package com.tiantian.web.controller.system;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import com.tiantian.common.core.controller.BaseController;
import com.tiantian.common.core.domain.ResponseResult;
import com.tiantian.common.core.domain.dto.SysNoticeDTO;
import com.tiantian.common.core.domain.entity.SysNotice;
import com.tiantian.common.core.page.TableDataInfo;
import com.tiantian.common.exception.BusinessException;
import com.tiantian.common.utils.JsonUtils;
import com.tiantian.framework.handler.NoticeWebSocketHandler;
import com.tiantian.system.service.SysNoticeService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;


/**
 * 信息操作处理
 *
 * @author TianTian
 */
@RestController
@RequestMapping("/system/notice")
@RequiredArgsConstructor
public class SysNoticeController extends BaseController {

    private final NoticeWebSocketHandler noticeWebSocketHandler;
    private final SysNoticeService sysNoticeService;

    private static final String INFO_NOTICE = "0";  // 普通消息
    private static final String WARN_NOTICE = "1";  // 警告消息
    private static final String ERROR_NOTICE = "2"; // 错误消息


    /**
     * 群发消息
     *
     * @param sysNoticeDTO 参数
     */
    @PostMapping
    @SaCheckPermission("notice")
    public ResponseResult<Void> sendMessage(@RequestBody @Valid SysNoticeDTO sysNoticeDTO) {
        checkParameter(sysNoticeDTO.getLevel());
        String jsonString = JsonUtils.toJsonString(sysNoticeDTO);
        noticeWebSocketHandler.sendToAllClient(jsonString);
        // 异步保存记录
        SysNotice sysNotice = BeanUtil.copyProperties(sysNoticeDTO, SysNotice.class);
        sysNotice.setCreateBy(getNickName());
        sysNotice.setCreateTime(LocalDateTime.now());
        sysNoticeService.insert(sysNotice);
        return ResponseResult.ok("消息发送成功");
    }

    /**
     * 分页查询
     *
     * @param sysNotice 参数参数
     */
    @GetMapping("/list")
    public TableDataInfo list(SysNotice sysNotice) {
        startPage();
        List<SysNotice> sysNoticeList = sysNoticeService.selectList(sysNotice);
        return getDataTable(sysNoticeList);
    }

    /**
     * 删除一条数据
     *
     * @param noticeId 主键
     */
    @DeleteMapping("/del/{noticeId}")
    public ResponseResult<Boolean> delete(@PathVariable Integer noticeId) {
        return ResponseResult.ok(sysNoticeService.deleteById(noticeId));
    }

    /**
     * 参数校验
     */
    private void checkParameter(String level) {
        if (!INFO_NOTICE.equals(level) && !WARN_NOTICE.equals(level) && !ERROR_NOTICE.equals(level)) {
            throw new BusinessException("参数错误只允许为字符串格式的[ 0 1 2 ]");
        }
    }
}
